package server

import (
	"encoding/json"
	"math/rand"
	"strconv"
	"time"

	openapi "github.com/alibabacloud-go/darabonba-openapi/client"
	dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v2/client"
	util "github.com/alibabacloud-go/tea-utils/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/tidwall/gjson"
)

// 短信初始化
func CreateClient() (_result *dysmsapi20170525.Client, _err error) {

	// 配置文件名
	systemInfo := "system.json"

	// 获取配置信息
	system := GetFile(systemInfo)

	// 短信配置
	accessKey_id := gjson.Get(system, "sms.accessKey_id").String()
	accessKey_secret := gjson.Get(system, "sms.accessKey_secret").String()

	config := &openapi.Config{
		AccessKeyId:     tea.String(accessKey_id),
		AccessKeySecret: tea.String(accessKey_secret),
	}
	// 访问的域名
	config.Endpoint = tea.String("dysmsapi.aliyuncs.com")
	_result = &dysmsapi20170525.Client{}
	_result, _err = dysmsapi20170525.NewClient(config)
	return _result, _err
}

// 发送短信
func SendMes(info map[string]string) (string, string) {

	phoneNum := info["phoneNum"]

	// 1登录 2变更密码 3变更重要信息
	var tpl string
	if info["tpl"] == "1" {
		tpl = "SMS_219740296"
	} else if info["tpl"] == "2" {
		tpl = "SMS_219735293"
	} else if info["tpl"] == "3" {
		tpl = "SMS_219740308"
	} else if info["tpl"] == "4" {
		tpl = "SMS_238155910"
	} else {
		tpl = "SMS_219740308"
	}

	client, _ := CreateClient()

	randNum := strconv.Itoa(GenerateRandInt(1000, 9999))

	tplParam := make(map[string]interface{})
	tplParam["code"] = randNum
	tplParamStr, _ := json.Marshal(tplParam)

	sendSmsRequest := &dysmsapi20170525.SendSmsRequest{
		PhoneNumbers:  tea.String(phoneNum),
		SignName:      tea.String("视云科技"),
		TemplateCode:  tea.String(tpl),
		TemplateParam: tea.String(string(tplParamStr)),
	}
	runtime := &util.RuntimeOptions{}
	sendMesRes, _ := client.SendSmsWithOptions(sendSmsRequest, runtime)

	return sendMesRes.GoString(), randNum
}

// 生成4位随机数
func GenerateRandInt(min, max int) int {
	rand.Seed(time.Now().UnixNano())
	return rand.Intn(max-min) + min
}
